local PhysicsLayer = require("app.PhysicsMgr").Layer
local GameLayer = class("GameLayer", function ()
    return cc.LayerColor:create(cc.c4b(0, 0, 0, 255))
end)

function GameLayer:ctor()
    self:enableNodeEvents()
    global.data = require("app.views.slots.GameData").getInstance()
    global.data:setData()
end

function GameLayer:onEnter()
    -- global.event:addEventListener("EVENT_ON_HP_DOWN", self, self._onHpDown)

    self:_addTouchHandler()
    self:_createWorld()
    self:_createUI()

    self:_registerKeyBoard()
    self:scheduleUpdate(handler(self, self.update))
end

function GameLayer:onExit()
    global.event:removeByTarget(self)
end

function GameLayer:_addTouchHandler()
    self:setTouchEnabled(true)
    self:setSwallowsTouches(false)
	self:registerScriptTouchHandler(function(state, x, y)
		if state == "began" then

		elseif state == "ended" then

		end
        return true
	end)
end

function GameLayer:_createWorld()
    local slotsMainNode = require("app.views.slots.SlotsMainNode").new()
    self:addChild(slotsMainNode)
    slotsMainNode:center()
    self._slotsMainNode = slotsMainNode
end

function GameLayer:_createUI()

end


function GameLayer:update(dt)
    if global.isPause then
        return
    end
    self._slotsMainNode:update(dt)
end

function GameLayer:_restart()
    self:performWithDelay(function ()
        self:removeFromParent(true)
        display.getRunningScene():addChild(require("app.views.GameLayer").new())
    end)
end

function GameLayer:_registerKeyBoard()
    local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
    local keypadListener = cc.EventListenerKeyboard:create()
    self._inputMap = {}
    keypadListener:registerScriptHandler(handler(self, self._keyPressedHandler), cc.Handler.EVENT_KEYBOARD_PRESSED)
    keypadListener:registerScriptHandler(handler(self, self._keyReleasedHandler), cc.Handler.EVENT_KEYBOARD_RELEASED)
    eventDispatcher:addEventListenerWithSceneGraphPriority(keypadListener, self)
end

function GameLayer:_keyPressedHandler(keyCode)
    self._inputMap[keyCode] = true
    if keyCode == cc.KeyCode.KEY_1 then
        require("app.editor.CocosRunningEditor"):setFontName("arial"):doEditor(true)
    elseif keyCode == cc.KeyCode.KEY_2 then
        dofile("src/app/debug.lua")
    elseif keyCode == cc.KeyCode.KEY_SPACE then
        local ts = cc.Director:getInstance():getScheduler():getTimeScale()
        cc.Director:getInstance():getScheduler():setTimeScale(ts == 0 and 1 or 0)
    end
end

function GameLayer:_keyReleasedHandler(keyCode)
    self._inputMap[keyCode] = false
end

function GameLayer:_isKeyPressing(keyCode)
    return self._inputMap[keyCode]
end

return GameLayer
